package com.koron.css2.serviceManage.service;


import com.koron.css2.serviceManage.bean.QuartzBean;
import com.koron.util.Constant;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.swan.bean.MessageBean;
@Component
public class JobUtil {
	private static Logger log = LogManager.getLogger(JobUtil.class);
	

   public static Scheduler scheduler;
     
   @Autowired
   public void setScheduler(Scheduler scheduler){
	   JobUtil.scheduler = scheduler;
   }

    
   /**
   * 新建一个任务
   * 
   */ 
   public static MessageBean<?> addJob(QuartzBean quartzBean) throws Exception {
	   log.debug("开始创建定时任务"+quartzBean.getJobName());
	   MessageBean<?> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success",void.class);
	   if (!CronExpression.isValidExpression(quartzBean.getCronExpression())) {
		   info.setCode(Constant.MESSAGE_INT_FAIL);
			info.setDescription("表达式格式不正确");
	        return info;
	    }  
	   //启动调度器  
      // scheduler.start(); 
       
       //构建job信息
       JobDetail jobDetail = JobBuilder.newJob(getClass(quartzBean.getJobClassName()).getClass()).withIdentity(quartzBean.getJobName(), Scheduler.DEFAULT_GROUP).build();

       //表达式调度构建器(即任务执行的时间)
       CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzBean.getCronExpression());

       //按新的cronExpression表达式构建一个新的trigger
       CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(quartzBean.getJobName(), Scheduler.DEFAULT_GROUP)
           .withSchedule(scheduleBuilder).build();

       try {
           scheduler.scheduleJob(jobDetail, trigger);
           log.debug("创建定时任务成功"+quartzBean.getJobName());
           return info;
       } catch (SchedulerException e) {
    	   log.error("创建定时任务失败"+e);
    	   info.setCode(Constant.MESSAGE_INT_FAIL);
    	   info.setDescription("创建定时任务失败"+e);
	       return info;
       }
    } 
     /**
     * 获取Job状态
     * @param jobName
     * @param jobGroup
     * @return
     * @throws SchedulerException
     */
     public static String getJobState(String jobName, String jobGroup) throws SchedulerException {       
       TriggerKey triggerKey = new TriggerKey(jobName, jobGroup);  
       return scheduler.getTriggerState(triggerKey).name();
      }
      
     //暂停所有任务

     public static void pauseAllJob() throws SchedulerException {      
       scheduler.pauseAll();
     }
     
   //暂停任务

    public static MessageBean<?> pauseJob(String jobName, String jobGroup) throws SchedulerException {      
      JobKey jobKey = new JobKey(jobName, jobGroup);
      JobDetail jobDetail = scheduler.getJobDetail(jobKey);
      if (jobDetail == null) {
         return MessageBean.create(Constant.MESSAGE_INT_FAIL, "暂停任务失败",void.class);
      }else {
         scheduler.pauseJob(jobKey);
         return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success",void.class);
      }
                      
    }
     
    //恢复所有任务

    public static void resumeAllJob() throws SchedulerException {      
      scheduler.resumeAll();
    }
     
    // 恢复某个任务

    public static MessageBean<?> resumeJob(String jobName, String jobGroup) throws SchedulerException {
       
      JobKey jobKey = new JobKey(jobName, jobGroup);
      JobDetail jobDetail = scheduler.getJobDetail(jobKey);
      if (jobDetail == null) {
    	  return MessageBean.create(Constant.MESSAGE_INT_FAIL, "恢复任务失败",void.class);
      }else {        
        scheduler.resumeJob(jobKey);
        return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success",void.class);
      }
    }
     
    //删除某个任务

    public static MessageBean<?> deleteJob(QuartzBean quartzBean) throws SchedulerException {      
      JobKey jobKey = new JobKey(quartzBean.getJobName(), quartzBean.getJobGroup());
      JobDetail jobDetail = scheduler.getJobDetail(jobKey);
      if (jobDetail == null ) {
    	  return MessageBean.create(Constant.MESSAGE_INT_FAIL, "任务不存在",void.class);
      }else if(!scheduler.checkExists(jobKey)) {
    	  return MessageBean.create(Constant.MESSAGE_INT_FAIL, "任务不存在",void.class);
      }else {
         scheduler.deleteJob(jobKey);
         return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success",void.class);
      } 
       
    }
     
    //修改任务

    public static MessageBean<?> modifyJob(QuartzBean quartzBean) throws SchedulerException {      
      if (!CronExpression.isValidExpression(quartzBean.getCronExpression())) {
    	  return MessageBean.create(Constant.MESSAGE_INT_FAIL, "cron表达式不正确",void.class);
      }
      TriggerKey triggerKey = TriggerKey.triggerKey(quartzBean.getJobName(),quartzBean.getJobGroup());      
      JobKey jobKey = new JobKey(quartzBean.getJobName(),quartzBean.getJobGroup());
      if (scheduler.checkExists(jobKey) && scheduler.checkExists(triggerKey)) {
        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);      
        //表达式调度构建器,不立即执行
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzBean.getCronExpression()).withMisfireHandlingInstructionDoNothing();
        //按新的cronExpression表达式重新构建trigger
        trigger = trigger.getTriggerBuilder().withIdentity(triggerKey)
          .withSchedule(scheduleBuilder).build();
        //修改参数
//        if(!trigger.getJobDataMap().get("invokeParam").equals(quartzBean.getInvokeParam())) {
//          trigger.getJobDataMap().put("invokeParam",quartzBean.getInvokeParam());
//        }        
        //按新的trigger重新设置job执行
        scheduler.rescheduleJob(triggerKey, trigger);                        
        return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success",void.class);       
      }else {
    	  return MessageBean.create(Constant.MESSAGE_INT_FAIL, "任务或触发器不存在",void.class);
      }  
       
    }
    public static Job getClass(String classname) throws Exception 
    {
        Class<?> class1 = Class.forName(classname);
        return (Job)class1.newInstance();
    }

}
